package org.ns.framework.datasource.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MapperProxy implements InvocationHandler {
    SqlSessionFactory sqlSessionFactory;
    String dataSourceName;
    MybatisDataSourceInjector mybatisDataSourceInjector;

    Class<?> mapperType;

    public MapperProxy(SqlSessionFactory sqlSessionFactory, String dataSourceName, MybatisDataSourceInjector mybatisDataSourceInjector, Class<?> mapperType) {
        this.sqlSessionFactory = sqlSessionFactory;
        this.dataSourceName = dataSourceName;
        this.mybatisDataSourceInjector = mybatisDataSourceInjector;
        this.mapperType = mapperType;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        TransactonManage transactonManage = TransactonManage.get();
        SqlSession sqlSession = null;

        try {
            if (transactonManage != null) {
                sqlSession = transactonManage.openSession(dataSourceName, sqlSessionFactory);
            } else {
                sqlSession = sqlSessionFactory.openSession(true);
            }

            Object mapper = sqlSession.getMapper(mapperType);

            return method.invoke(mapper, args);
        } catch (Throwable e) {
            throw e;
        } finally {
            if (transactonManage == null && sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}
